package com.zyw.customcalendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TimePicker;

import com.zyw.customcalendar.common.dialog.CommonDialog;
import com.zyw.customcalendar.common.util.DialogItemAdapter;
import com.zyw.customcalendar.dao.CalendarSQLiteDao;
import com.zyw.customcalendar.event.EventIndex;
import com.zyw.customcalendar.model.EventModel;

public class EventActivity extends Activity{

	private TextView textCongfu, textDate, textTime, textEndDate, textEndTime,
			textChixu, textContent,textNote,textLocation;

	private ArrayList<Map<String,Object>> tlist;

	private ArrayList<Map<String,Object>> tlist1;

	private Button btnSubmit,btnSave,btnCacel;
	private boolean mCreateStatus = true;
	private EventModel mEventModel;

	//private int mScreenWidth,mScreenHeight;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event);

		InitData();
		InitView();

		updateViewByIntent();
	}

	private void updateViewByIntent() {
		mEventModel = (EventModel) getIntent().getSerializableExtra("event_model");
		if(mEventModel != null){
			mCreateStatus = false;
			updateViewStatus(mCreateStatus);
			textContent.setText(mEventModel.content);
			textNote.setText(mEventModel.noteContent);
			textLocation.setText(mEventModel.location);
			textDate.setText(mEventModel.startDate);
			textEndDate.setText(mEventModel.endDate);

			textTime.setText(getEventTime(mEventModel.startDate, mEventModel.startTime));
			textEndTime.setText(getEventTime(mEventModel.endDate, mEventModel.endTime));

			textChixu.setText(mEventModel.chixuIndex);
			textCongfu.setText(mEventModel.chongfuIndex);
		}
	}

	private String getEventTime(String date, String dateAndTime){
		return dateAndTime.substring(date.length()).trim();
	}

	private void updateViewStatus(boolean editable) {
		//隐藏提交按钮
		btnSubmit.setText(
				editable == true ? "提交" : "修改");
		//设置不可点击
		textCongfu.setClickable(editable);
		textDate.setClickable(editable);
		textTime.setClickable(editable);
		textEndDate.setClickable(editable);
		textEndTime.setClickable(editable);
		textChixu.setClickable(editable);
		textContent.setInputType(editable == false ?
				InputType.TYPE_NULL : InputType.TYPE_CLASS_TEXT);
		textNote.setInputType(editable == false ?
				InputType.TYPE_NULL : InputType.TYPE_CLASS_TEXT);
		textLocation.setInputType(editable == false ?
				InputType.TYPE_NULL : InputType.TYPE_CLASS_TEXT);
	}

	private void updateButtonStatus(boolean isChange) {
		btnSubmit.setVisibility(isChange ? View.GONE : View.VISIBLE);
		btnSave.setVisibility(isChange ? View.VISIBLE : View.GONE);
		btnCacel.setVisibility(isChange ? View.VISIBLE : View.GONE);

		updateViewStatus(isChange);
	}

	private String[] chixu = {
			"0 分钟","30 分钟","1 小时","2 小时","全天","自定义"
	};
	private String[] chongfu = {
			"一次性活动","每天","每个工作日","每周","每月","每年"
	};

	public void InitData(){
		if(tlist != null){
			tlist.clear();
		}else{
			tlist = new ArrayList<>();
		}

		if(tlist1 != null){
			tlist1.clear();
		}else{
			tlist1 = new ArrayList<>();
		}

		for(int i = 0; i < chongfu.length; i++){
			Map<String,Object> tmap = new HashMap<>();
			tmap.put("dialog_list_context", chongfu[i]);
			tmap.put("dialog_list_position", i);
			tmap.put("dialog_list_check", false);
			if(i == 0)
				tmap.put("dialog_list_check", true);
			tlist1.add(tmap);
		}

		for(int i = 0; i < chixu.length; i++){
			Map<String,Object> tmap = new HashMap<>();
			tmap.put("dialog_list_context", chixu[i]);
			tmap.put("dialog_list_position", i);
			tmap.put("dialog_list_check", false);
			if(i == 0)
				tmap.put("dialog_list_check", true);
			tlist.add(tmap);
		}
	}

	public void InitView(){
		textCongfu = (TextView) findViewById(R.id.text_congfu_event);
		textCongfu.setOnClickListener(setClickListener());
		textCongfu.setText(chongfu[0]);

		textDate = (TextView) findViewById(R.id.text_date_event);
		textDate.setOnClickListener(setClickListener());
		textTime = (TextView) findViewById(R.id.text_time_event);
		textTime.setOnClickListener(setClickListener());

		textEndDate = (TextView) findViewById(R.id.text_date_end);
		textEndDate.setOnClickListener(setClickListener());
		textEndTime = (TextView) findViewById(R.id.text_time_end);
		textEndTime.setOnClickListener(setClickListener());

		textChixu = (TextView) findViewById(R.id.text_chixu_event);
		textChixu.setOnClickListener(setClickListener());
		textChixu.setText(chixu[0]);

		textContent = (TextView) findViewById(R.id.text_content_event);
		textContent.setOnClickListener(setClickListener());
		textContent.addTextChangedListener(setTextWatcher());

		textNote = (TextView) findViewById(R.id.text_note_content);

		textLocation = (TextView) findViewById(R.id.text_location);

		String selectDaysString = getIntent().getStringExtra("selectDaysString");
		String selectTimesString = getIntent().getStringExtra("selectTimesString");
		if(selectDaysString != null && selectTimesString != null) {
			textDate.setText(selectDaysString);
			textTime.setText(selectTimesString);

			textEndDate.setText(selectDaysString);
			textEndTime.setText(selectTimesString);
		}

		btnSubmit = (Button) findViewById(R.id.btn_shijian_submit);
		btnSubmit.setOnClickListener(setClickListener());
		btnSubmit.setTextColor(getResources().getColor(R.color.btn_unsubmit_color, null));

		btnSave = (Button) findViewById(R.id.btn_shijian_save);
		btnSave.setOnClickListener(setClickListener());

		btnCacel = (Button) findViewById(R.id.btn_shijian_cancel);
		btnCacel.setOnClickListener(setClickListener());
	}

	private TextWatcher setTextWatcher(){
		TextWatcher textWatcher = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub

			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
										  int arg3) {
				// TODO Auto-generated method stub

			}
			@Override
			public void afterTextChanged(Editable editable) {
				// TODO Auto-generated method stub
				if ("".equals(editable.toString())){
					btnSubmit.setTextColor(getResources().getColor(R.color.btn_unsubmit_color, null));
				}else{
					btnSubmit.setEnabled(true);
					btnSubmit.setTextColor(getResources().getColor(R.color.btn_submit_color, null));
				}
			}
		};
		return textWatcher;
	}

	private OnClickListener setClickListener(){
		OnClickListener listener = new OnClickListener() {
			@SuppressWarnings("static-access")
			@Override
			public void onClick(final View view) {
				// TODO Auto-generated method stub
				if(textCongfu.equals(view)){
					showAlertDialog(view, tlist1);
				}else if(textChixu.equals(view)){
					showAlertDialog(view, tlist);
				}else if(btnSubmit.equals(view)){
					if(!mCreateStatus){
						updateButtonStatus(true);
						return;
					}
					saveEvent();
					setResult(1);
					finish();
				}else if(btnSave.equals(view)){
					saveEvent();
					finish();
				}else if(btnCacel.equals(view)){
					updateButtonStatus(false);
				}else if(textDate.equals(view) || textEndDate.equals(view)){
					Calendar calendar = Calendar.getInstance();
					new DatePickerDialog(EventActivity.this, new OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker dataPicker, int year,
											  int month, int day) {
							// TODO Auto-generated method stub
							month = month + 1;
							String dateString = year + "/" + month + "/" + day;
							((TextView)view).setText(dateString);
						}
					}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
							calendar.get(Calendar.DAY_OF_MONTH)).show();
				}else if(textTime.equals(view) || textEndTime.equals(view)){
					Calendar calendar = Calendar.getInstance();
					new TimePickerDialog(EventActivity.this, new OnTimeSetListener(){
						@Override
						public void onTimeSet(TimePicker arg0, int HOUR,
											  int MINUTE) {
							// TODO Auto-generated method stub
							String timeString = HOUR + ":" + MINUTE;
							((TextView)view).setText(timeString);
						}
					}, calendar.HOUR_OF_DAY, calendar.MINUTE, true).show();
				}
			}
		};
		return listener;
	}

	private void saveEvent(){
		CalendarSQLiteDao sqliteDao = new CalendarSQLiteDao(EventActivity.this);
		if(mEventModel == null) {
			mEventModel = new EventModel();
		}
		mEventModel.userId = "666";
		mEventModel.content = textContent.getText().toString();
		mEventModel.startDate = textDate.getText().toString();
		mEventModel.startTime = textDate.getText().toString()
				+ " " + textTime.getText().toString();

		mEventModel.endDate = textEndDate.getText().toString();
		mEventModel.endTime = textEndDate.getText().toString()
				+ " " + textEndTime.getText().toString();

		mEventModel.location = textLocation.getText().toString();

		mEventModel.noteContent = textNote.getText().toString();

		mEventModel.chixuIndex = textChixu.getText().toString();
		mEventModel.chongfuIndex = textCongfu.getText().toString();
		sqliteDao.setData(mEventModel);
	}



	private DialogItemAdapter adapter;
	private PopupWindow popWindow;
	public void showAlertDialog(View v, ArrayList<Map<String,Object>> tlist){
		int vWidth = v.getWidth();
		int tx = vWidth - AppApplication.DEVICE_WIDTH/2;//计算X轴上的偏移量
		popWindow = CommonDialog.PopUpWindow(getDialogView(R.layout.dialog_drop_item_view, v, tlist),
				v, getResources().getDrawable(R.drawable.dialog_bg, null),
				AppApplication.DEVICE_WIDTH / 2, AppApplication.DEVICE_HEIGHT / 3, tx, 0);
	}

	@SuppressLint("InflateParams")
	public View getDialogView(int resource, final View v,
							  final ArrayList<Map<String,Object>> tlist){
		View view = LayoutInflater.from(EventActivity.this).
				inflate(R.layout.dialog_dropdown_view, null);
		//获取ListView
		ListView list = (ListView) view.findViewById(R.id.dialog_list);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position,
									long position2) {
				// TODO Auto-generated method stub
				if(popWindow != null && popWindow.isShowing()){
					for(int i = 0; i < tlist.size(); i++){
						Map<String,Object> map = tlist.get(i);
						map.put("dialog_list_check", false);
					}
					Map<String,Object> map = tlist.get(position);
					map.put("dialog_list_check", true);
					((TextView)v).setText(map.get("dialog_list_context").toString());
					popWindow.dismiss();
				}
			}
		});
		adapter = new DialogItemAdapter(tlist, resource, EventActivity.this);
		list.setAdapter(adapter);
		return view;
	}
}
